<template>
	<div>
    <el-dialog :title='title' :visible.sync="isShow" @open="openCollback" :lock-scroll="false" width="80%" @close="closeDialog">
      <el-card v-loading="loading">
        <el-form ref='rowData1' :model='rowData1' size='small' :rules="rules" label-width="100px">
          <el-row :gutter="10">
            <el-col :span="13">
            <el-form-item label="机构名称" prop="branchNO">
              <!-- <el-popover placement="bottom" width="200" trigger="click" v-model="popoverShow">
                <el-tree :data="treedata" :highlight-current="true" :expand-on-click-node="false" default-expand-all
                 @node-click="handleNodeClick" :props="defaultProps">
                </el-tree>
                <el-input slot="reference" size="small" v-model="rowData1.branchName" placeholder="请选择机构"
                  :disabled="title=='修改加班'"></el-input>
              </el-popover> -->
              <el-input v-model.trim="rowData1.branchName" size="small" :disabled="title=='修改加班'" v-if="title=='修改加班'"></el-input>
              <select-tree :tree-data="treedata" :branch="rowData1.branchName" @getBranchName="getBranch" v-if="title!='修改加班'"></select-tree>
            </el-form-item>
          </el-col>
            <el-col :span="13">
              <el-form-item label="加班编号" prop="OTID" v-if="type=='edit'">
                <el-input v-model.trim="rowData1.OTID" maxlength="60" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="13">
              <el-form-item label="加班名称" prop="OTNAME">
                <el-input v-model.trim="rowData1.OTNAME" maxlength="60" placeholder="请输入加班名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="13">
              <el-form-item label='活动类型' prop='ACTIVITYTYPE'>
                <el-select v-model='rowData1.ACTIVITYTYPE' clearable size="small" placeholder="请选择活动类型">
                  <el-option v-for="item in actOptions" :key="item.ACTIVITYTYPE" :label="item.ACTIVITYTYPENAME"
                    :value="item.ACTIVITYTYPE"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="13">
              <el-form-item label="时长" prop="HOURS">
                <el-time-picker size="small"
                  v-model="rowData1.HOURS"
                  format="HH:mm"
                  value-format="HH:mm"
                  @focus="rowData1.HOURS===null || rowData1.HOURS===''?rowData1.HOURS='00:00':rowData1.HOURS"
                  style="width: 100%" placeholder="请选择时长">
                </el-time-picker>
              </el-form-item>
            </el-col>
             </el-row>
          <el-row>
            <el-col :span="13">
              <el-form-item label="最小时间间隔" prop="MININTERVAL">
                <el-time-picker size="small"
                  v-model="rowData1.MININTERVAL"
                  @focus="rowData1.MININTERVAL===null || rowData1.MININTERVAL===''?rowData1.MININTERVAL='00:00':rowData1.MININTERVAL"
                  format="HH:mm"
                  value-format="HH:mm"
                  style="width: 100%" placeholder="请选择最小时间间隔">
                </el-time-picker>
              </el-form-item>
            </el-col>
            <el-col :span="13">
              <el-form-item label="最大时间间隔" prop="MAXINTERVAL">
                <el-time-picker size="small"
                  v-model="rowData1.MAXINTERVAL"
                  @focus="rowData1.MAXINTERVAL===null || rowData1.MAXINTERVAL===''?rowData1.MAXINTERVAL='00:00':rowData1.MAXINTERVAL"
                  format="HH:mm"
                  value-format="HH:mm"
                  style="width: 100%" placeholder="请选择最大时间间隔">
                </el-time-picker>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="说明" prop="NOTES">
                <el-input type="textarea" :rows="2"  v-model.trim="rowData1.NOTES" maxlength="300" placeholder="请输入说明"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="margin-bottom:20px;">
            <el-col :span="23">
              <el-collapse v-model="activeNames" style="margin-left:5%;">
                <el-collapse-item name="1">
                  <template slot="title">
                    关联的班次事件<i class="header-icon el-icon-info"></i>
                  </template>
                  <el-table :data="EVENT">
                    <el-table-column prop="CLASSESEVENTID" label="班次事件编号" width="120"></el-table-column>
                    <el-table-column prop="CLASSESEVENTNAME" label="班次事件名称" width="120"></el-table-column>
                    <el-table-column prop="ACTIVITYTYPE" label="活动类型"></el-table-column>
                    <el-table-column prop="HOURS" label="时长"></el-table-column>
                    <el-table-column prop="SRTTIMETYPE" label="开始时间类型"></el-table-column>
                    <el-table-column prop="EARLIESTSRTTIME" label="最早开始时间"></el-table-column>
                    <el-table-column prop="LATESTSRTTIME" label="最晚开始时间"></el-table-column>
                    <el-table-column prop="ISPAID" label="是否带薪">
                      <template slot-scope="scope">
                        <span>{{scope.row.ISPAID === "1"?"是":"否"}}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="最少次数" prop="MINTIMES" width="100"></el-table-column>
                    <el-table-column label="最多次数" prop="MAXTIMES" width="100"></el-table-column>
                    <el-table-column prop="NOTES" label="说明"></el-table-column>
                    <el-table-column label="操作" fixed="right">
                      <template slot-scope="scope">
                        <el-tooltip class="item" effect="dark" content="删除事件" placement="top">
                          <el-button type="text" style="margin-left:0px" @click="delEvent(scope.row)">
                            <i class="el-icon-delete"></i>
                          </el-button>
                        </el-tooltip>
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-col :span="4" :offset="19" style="margin-top:10px;margin-bottom:10px;">
                    <el-button type="primary" size="mini" icon="el-icon-plus" @click="addClass()">新增关联班次事件</el-button>
                  </el-col>
                </el-collapse-item>
              </el-collapse>
            </el-col>
          </el-row>
        </el-form>
        <div class="box" style="text-align:right;">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage" 
            :page-sizes="[5]"  
            :page-size="pageSize" 
            layout="prev, pager, next" 
            :total="tableTotal">
          </el-pagination>
        </div>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button @click="option.isShow = false;" size="mini">取 消</el-button>
        <el-button type="primary" @click="EditModel('rowData1')" size="mini">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 关联班次事件的dialog -->
    <el-dialog title="关联班次事件" append-to-body :visible.sync="eventIsShow" :close-on-click-modal="false" width="80%"
      @open="openEventDialog">
      <el-table :data="tableData" ref="multipleTable" @selection-change="changeFun" @select="selectMemoryFn"
        @select-all="selectAll">
        <el-table-column type="selection" width="55" :selectable="checkboxInit">
        </el-table-column>
        <el-table-column prop="CLASSESEVENTID" label="班次事件编号" width="120"></el-table-column>
        <el-table-column prop="CLASSESEVENTNAME" label="班次事件名称" width="120"></el-table-column>
        <el-table-column prop="ACTIVITYTYPE" label="活动类型"></el-table-column>
        <el-table-column prop="HOURS" label="时长"></el-table-column>
        <el-table-column prop="SRTTIMETYPE" label="开始时间类型"></el-table-column>
        <el-table-column prop="EARLIESTSRTTIME" label="最早开始时间"></el-table-column>
        <el-table-column prop="LATESTSRTTIME" label="最晚开始时间"></el-table-column>
        <el-table-column prop="ISPAID" label="是否带薪">
          <template slot-scope="scope">
            <span>{{scope.row.ISPAID === "1"?"是":"否"}}</span>
          </template>
        </el-table-column>
        <el-table-column label="最少次数" prop="MINTIMES" width="100"></el-table-column>
        <el-table-column label="最多次数" prop="MAXTIMES" width="100"></el-table-column>
        <el-table-column prop="NOTES" label="说明"></el-table-column>
      </el-table>
      <div class="box" style="text-align:right;">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page.sync="currentPage" :page-sizes="[5]" :page-size="pageSize" layout="prev, pager, next"
          :total="tableTotal">
        </el-pagination>
      </div>
      <el-row>
        <el-col :span="8" :offset="16" style="margin-top:10px;">
          <el-button type="primary" size="small" @click="saveEvent">保存</el-button>
          <el-button size="small" @click="cancelEvent">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
	</div>
</template>

<script>
// import request from "@/utils/requestKnowledgeCluster"
import getGlobalParams from "@/common/utils/getGlobalParams";
import requestWFM from "@/common/utils/requestWFM";
import addOTDelay from '@/message/wfm/scheduleDataManage/OTDelayManage/addOTDelay';
import editOTDelay from '@/message/wfm/scheduleDataManage/OTDelayManage/editOTDelay';
import classEventQuery from '@/message/wfm/scheduleDataManage/classEventManage/classEventQuery';
import selectTree from "@/components/selectTree5/";
export default {
  components: {
    selectTree
  },
  props: {
    option: Object,
    rowData: Object,
    title: String,
    type: String,
    treedata: Array,
    actOptions: Array
  },
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'BRANCHNAME'
      },
      popoverShow: false,
      loading: false,
      tableData: [],
      currentPage: 1,
      pageSize: 5,
      tableTotal: 0,
      rules: {
        OTNAME: [
          { required: true, message: '请输入加班名称', trigger: 'blur' }
        ],
        ACTIVITYTYPE: [
          { required: true, message: '请选择活动类型', trigger: 'change' }
        ],
        HOURS: [
          { required: true, message: '请输入时长', trigger: 'blur' }
        ],
      },
      multipleSelection: [], // 选中的数据二维数组
      CLASSESEVENTID: [], // 选中的数据CLASSESEVENTID数组
      checkList: [], //选中数列
      EVENT:[],
      rowData1: {
        ACTIVITYTYPE: '',
        ACTIVITYTYPENAME: '',
        CLASSESEVENTIDLIST: '',
        EVENT: '',
        HOURS: '',
        MAXINTERVAL: '',
        MININTERVAL: '',
        NOTES: '',
        OTID: '',
        OTNAME: '',
        branchNO: '',
        branchName: '',
      },
      activeNames: ['1'],
      eventIsShow: false, //关联班次事件的isShow
    };
  },
  computed: {
    isShow: {
      get: function() {
        return this.option.isShow;
      },
      set: function(newVal) {
        this.option.isShow = newVal;
      }
    },
  },
  created() {

  },
  watch: {
    tableData (oldVal, newVal) { // 监听数据变化，然后执行分页记忆自动选中回调
      this.$nextTick(() => {
        this.selectMemoriedDataFn();
      })
    },
  },
  methods: {
    addClass(){
      if(this.rowData1.branchNO == ''){
        this.$message({
          type: "error",
          message: "请先选择机构"
        });
        return;
      }else{
        this.eventIsShow = true;
      }
    },
    getBranch(data) {
      this.rowData1.branchNO= data.BRANCHNO
      this.rowData1.branchName= data.BRANCHNAME
      this.popoverShow =false
    },
    checkboxInit(row,index){
      if (this.checkList.indexOf(row.CLASSESEVENTID)!=-1) 
        return false;//不可勾选
      else
        return true;//可勾选
    },
    // 打开dialog回调
    openCollback() {
      this.$nextTick(() => {
        this.$refs["rowData1"].clearValidate();
      });
      if(this.$parent.PopType == 'edit'){
        this.rowData1 = JSON.parse(JSON.stringify(this.rowData)); 
        this.checkList = this.rowData1.CLASSESEVENTIDLIST?this.rowData1.CLASSESEVENTIDLIST.split(','):[];
      }
      this.EVENT = this.rowData1.EVENT || [];
      console.log(this.rowData1);
    },
    //关闭弹窗
    closeDialog() {
      this.currentPage= 1;
      this.multipleSelection = [];
      this.checkList = [];
      this.EVENT = [];
      this.rowData1={
        ACTIVITYTYPE: '',
        ACTIVITYTYPENAME: '',
        CLASSESEVENTIDLIST: '',
        EVENT: '',
        HOURS: '',
        MAXINTERVAL: '',
        MININTERVAL: '',
        NOTES: '',
        OTID: '',
        OTNAME: '',
        branchNO: '',
        branchName: '',
      };
    },
    EditModel(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let classId = []
          this.EVENT.forEach(item => {
            classId.push(item.CLASSESEVENTID)
          })
          if(this.$parent.PopType == 'add'){
            // 执行新增操作
            this.addOTDelay(classId);
          }else{
            // 执行修改操作
            this.editOTDelay(classId);
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    async addOTDelay(classId) { 
      this.loading = true;
      let resBody = new addOTDelay();
      resBody.data.BRANCHNO = this.rowData1.branchNO;
      resBody.data.OTNAME = this.rowData1.OTNAME;
      resBody.data.ACTIVITYTYPE = this.rowData1.ACTIVITYTYPE;
      resBody.data.NOTES = this.rowData1.NOTES;
      resBody.data.HOURS = this.rowData1.HOURS;
      resBody.data.MININTERVAL = this.rowData1.MININTERVAL;
      resBody.data.MAXINTERVAL = this.rowData1.MAXINTERVAL;
      resBody.data.CLASSESEVENTIDLIST = classId.join(',');
      let response = await requestWFM(resBody);
      this.loading = false;
      this.option.isShow = false;
      if (response.SYS_HEAD.ReturnCode == "000000") {
        this.$parent.queryModel();
        this.$message({
          type: "success",
          message: '添加成功'
        });
      }else {
        this.$message({
          type: "error",
          message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
        });
      }
    },
    // 编辑加班
    async editOTDelay(classId) { 
      this.loading = true;
      let resBody = new editOTDelay();
      resBody.data.OTID = this.rowData1.OTID;
      resBody.data.OTNAME = this.rowData1.OTNAME;
      resBody.data.ACTIVITYTYPE = this.rowData1.ACTIVITYTYPE;
      resBody.data.NOTES = this.rowData1.NOTES;
      resBody.data.HOURS = this.rowData1.HOURS;
      resBody.data.MININTERVAL = this.rowData1.MININTERVAL;
      resBody.data.MAXINTERVAL = this.rowData1.MAXINTERVAL;
      resBody.data.CLASSESEVENTIDLIST = classId.join(',');
      let response = await requestWFM(resBody);
      this.loading = false;
      this.option.isShow = false;
      if (response.SYS_HEAD.ReturnCode == "000000") {
        this.$parent.queryModel();
        this.$message({
          type: "success",
          message: '修改成功'
        });
      }else {
        this.$message({
          type: "error",
          message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
        });
      }
    },
    async queryModel() {
      var that = this;
      this.loading = true;
      let resBody = new classEventQuery();
      resBody.data.BRANCHNO = this.rowData1.branchNO;
      resBody.data.CLASSESEVENTID = '';
      resBody.data.CLASSESEVENTNAME = '';
      resBody.data.CurrPage = this.currentPage + "";
      resBody.data.PageRowNum = this.pageSize + "";
      let response = await requestWFM(resBody);
      this.loading = false;
      if (response.SYS_HEAD.ReturnCode == "000000") {
        this.tableData = response.BODY.RSPSTRUCT;
        this.tableTotal = response.BODY.TotalRowNum;
      }
      else if (response.SYS_HEAD.ReturnCode == "ARBFQ001") {
        this.tableData = [];
        this.tableTotal = 0;
      }
      else {
        this.$message({
          type: "error",
          message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
        });
      }
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.queryModel();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.queryModel();
    },
    changeFun(val) {
      this.$nextTick(() => {
        let CLASSESEVENTID = []
        this.multipleSelection.forEach(L => L.forEach(M => CLASSESEVENTID.push(M.CLASSESEVENTID)))
        this.CLASSESEVENTID = CLASSESEVENTID;
        // console.log(this.CLASSESEVENTID);
      })
    },
    selectAll (selection) { // 全选切换方法
      if (selection.length) { // 全选
        this.multipleSelection[this.currentPage-1] = selection
      } else { // 全不选
        this.multipleSelection[this.currentPage-1] = []
      }
    },
    selectMemoryFn (val, row) { // 设置分页记忆二位数组方法
      // 注意：val 传过来默认为数组类型 ，row 为 Object（当前选择数据对象）
      let currentArr = this.multipleSelection[this.currentPage-1] // 当前分页对应数组
      if (!currentArr) {
        this.multipleSelection[this.currentPage-1] = val // 不存在这个二维数组，则创建这个二位数组
      } else { // 存在
        if (val.includes(row)) { // 选中
          this.multipleSelection[this.currentPage-1] = val
        } else { // 取消
          for(var i=0;i<currentArr.length;i++){
            if(currentArr[i]){
              if(currentArr[i].CLASSESEVENTID == row.CLASSESEVENTID){
                delete currentArr[i];
                break;
              }
            }
          }
          // delete currentArr[currentArr.indexOf(row)]
        }
      }
    },
    selectMemoriedDataFn () { // 分页记忆自动选中方法
      let currentArr = this.multipleSelection[this.currentPage-1]  // 当前分页对应被选中数据

      if (currentArr && currentArr.length) { // 存在则继续执行
        let tempRowsIDs = this.tableData.map(L => L.CLASSESEVENTID) // 当前分页被选中数据的id集合
        currentArr.forEach((item, index) => { // 遍历当前分页被选中数据
          if (tempRowsIDs.includes(item.CLASSESEVENTID)) { // id匹配上，则选中
            this.$refs.multipleTable.toggleRowSelection(this.tableData[tempRowsIDs.indexOf(item.CLASSESEVENTID)])
          }
        })
      }
    },
    // 去重
    uniqueArr(array) {
      var n = []; //一个新的临时数组
      //遍历当前数组
      for (var i = 0; i < array.length; i++) {
        //如果当前数组的第i已经保存进了临时数组，那么跳过，
        //否则把当前项push到临时数组里面
        if (n.indexOf(array[i]) == -1) n.push(array[i]);
      }
      return n;
    },
    delCon(index){	
      this.checkList = this.remove(this.checkList,index.CLASSESEVENTID);
      var result=[];  
      // 删除数组中指定数据
      for(var i=0; i<this.EVENT.length; i++){  
        if(this.EVENT[i].CLASSESEVENTID!=index.CLASSESEVENTID){  
            result.push(this.EVENT[i]);  
        }  
      } 
      this.EVENT = result;
    },
    // 删除数组中指定数据
    remove(arr, item) {  
      var result=[];  
      for(var i=0; i<arr.length; i++){  
        if(arr[i]!=item){  
            result.push(arr[i]);  
        }  
      }  
      return result;  
    },
    // 保存所选的班次事件
    saveEvent() {
      this.multipleSelection.forEach(item => {
        item.forEach(i => {
          this.EVENT.push(i)
        })
      })
      this.eventIsShow = false
    },
    delEvent(row) {
      let i
      this.EVENT.forEach((item, index) => {
        if (item.CLASSESEVENTID === row.CLASSESEVENTID) {
          i = index
        }
      });
      this.EVENT.splice(i, 1)
      // console.log(this.EVENT)
    },
    // 打开关联班次事件的dialog
    openEventDialog() {
      this.currentPage = 1;
      this.multipleSelection = [];
      this.queryModel()
    },
    // 取消所选的班次事件
    cancelEvent() {
      this.eventIsShow = false
    },
  }
};
</script>

<style>
.sortable-ghost {
  opacity: 0.8;
  color: #fff !important;
  background: #42b983 !important;
}
</style>

<style lang="scss" scoped>
.icon-star {
  margin-right: 2px;
}
.drag-handler {
  width: 20px;
  height: 20px;
  cursor: pointer;
}
.mouseDrag {
  cursor: move;
}
.slotFooter {
  text-align: right;
}
ol{
  padding: 0;
  margin: 0;
}
.tips{
  width: 100%;
  padding: 8px 16px;
  margin: 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
  opacity: 1;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-transition: opacity .2s;
  transition: opacity .2s;
  background-color: #f0f9eb;
  color: #67C23A;
  margin-top: 5px;
  .el-icon-delete{
    font-size: 12px;
    color: #C0C4CC;
    opacity: 1;
    position: absolute;
    top: 12px;
    right: 15px;
    cursor: pointer;
  }
}
</style>
